package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.JwtClaimsConstant;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.JwtProperties;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.JwtUtil;
import com.sky.vo.UserLoginVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class UserServiceImpl implements UserService {
    @Autowired
    private WeChatProperties weChatProperties;
    @Autowired
    private JwtProperties jwtProperties;
    @Autowired
    private UserMapper userMapper;

    public UserLoginVO login(UserLoginDTO userLoginDTO) {
        //发送请求给微信获取openid
        HttpClientUtil httpClientUtil = new HttpClientUtil();
        Map<String, String> loginmap = new HashMap<>();
        loginmap.put("appid", weChatProperties.getAppid());
        loginmap.put("secret", weChatProperties.getSecret());
        loginmap.put("js_code", userLoginDTO.getCode());
        loginmap.put("grant_type", "authorization_code");
        String doGet = httpClientUtil.doGet("https://api.weixin.qq.com/sns/jscode2session", loginmap);
        log.info(doGet);
        JSONObject jsonObject = JSONObject.parseObject(doGet);
        String openid = (String) jsonObject.get("openid");
        //openid获取失败抛出业务异常
        if (openid == null) {
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }

        UserLoginVO userLoginVO = new UserLoginVO();
        //判断是否是新用户,添加id字段
        User user = userMapper.searchUser(openid);
        if (user == null) {
            user = User.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                    .build();
            userMapper.addUser(user);
        }

        //用户唯一标识生成JWT令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID, user.getId());
        String jwt = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), claims);
        log.info(jwt);
        userLoginVO.setId(user.getId());
        userLoginVO.setOpenid(openid);
        userLoginVO.setToken(jwt);
        return userLoginVO;
    }
}
